package com.bosssoft.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bosssoft.entity.dto.FibRoleDTO;
import com.bosssoft.entity.po.FibRoleAuthPO;
import com.bosssoft.entity.po.FibRolePO;
import com.bosssoft.entity.vo.FibRoleAuthVO;
import com.bosssoft.entity.vo.FibRoleVO;
import com.bosssoft.entity.vo.FibUserRoleVO;
import com.bosssoft.enums.CopyPropertityEnum;
import com.bosssoft.exception.DaoException;
import com.bosssoft.page.PageResult;
import com.bosssoft.response.Result;
import com.bosssoft.service.FibRoleService;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author 项昊天
 * @create 2021/8/17 11:33
 */
@Slf4j
@RestController
@RequestMapping("/role")
public class RoleController {

    @Resource
    FibRoleService roleService;

    @Autowired
    RedisTemplate<String, String> redisTemplate;

    @PostMapping("/save")
    public Result saveRole(@RequestBody @Validated FibRoleVO roleVO) {
        try {
            Byte deleted = 1;
            roleVO.setDeleted(deleted);
            FibRoleDTO roleDTO = new FibRoleDTO();
            BeanUtils.copyProperties(roleVO, roleDTO);
            if (roleService.addRole(roleDTO)) {
                return Result.ok().message("添加角色成功!");
            }
            return Result.error().message("添加角色失败!角色已存在!");
        } catch (Exception e) {
            throw DaoException.error().setCodeAndMessage(CopyPropertityEnum.RESOURCE_NULL_ERROR);
        }
    }

    /**
     * 分页查询
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @PostMapping("/getRolePage")
    public Result getRolePage(@RequestParam(defaultValue = "1") Integer pageNo,
                              @RequestParam(defaultValue = "10") Integer pageSize, FibRoleVO fibRoleVO) {
        try {
            QueryWrapper<FibRolePO> queryWrapper = new QueryWrapper<>();
            if (ObjectUtil.isNotNull(fibRoleVO.getRoleId())) {
                queryWrapper.like("role_id", fibRoleVO.getRoleId());
            }
            if (ObjectUtil.isNotNull(fibRoleVO.getRoleName())) {
                queryWrapper.like("role_name", fibRoleVO.getRoleName());
            }
            Page<FibRolePO> page = new Page<>(pageNo, pageSize);
            Page<FibRolePO> rolePage = roleService.page(page, queryWrapper);
            long total = rolePage.getTotal();
            List<FibRolePO> recordPOs = rolePage.getRecords();
            PageResult<FibRolePO> results = new PageResult<>(page, recordPOs);
            return Result.ok().data("total", total)
                    .data("page", results)
                    .data("pageNo", pageNo);
        } catch (Exception e) {
            log.info("getRolePage出现异常");
            throw DaoException.error(CopyPropertityEnum.RESOURCE_NULL_ERROR);
        }
    }

    @PutMapping("/modify")
    public Result modifyRole(@RequestBody @Validated FibRoleVO roleVO) {
        try {
            FibRoleDTO roleDTO = new FibRoleDTO();
            BeanUtils.copyProperties(roleVO, roleDTO);
            if (roleService.modifyRole(roleDTO)) {
                return Result.ok().message("修改角色成功!");
            }
            return Result.error().message("修改角色失败!");
        } catch (Exception e) {
            throw DaoException.error().setCodeAndMessage(CopyPropertityEnum.RESOURCE_NULL_ERROR);
        }
    }

    @PutMapping("/ban/{id}/{status}")
    public Result banRole(@PathVariable("id") Long id,
                          @PathVariable("status") Integer status) {
        if (roleService.banRoleById(id, status)) {
            return Result.ok().message("操作成功!");
        }
        return Result.error().message("操作失败!");
    }

    @DeleteMapping("/delete")
    public Result delRole(@RequestBody FibRoleVO roleVO) {
        if (roleVO.getRoleId() != null && roleService.deleteRoleById(roleVO.getRoleId())) {
            return Result.ok().message("删除角色成功!");
        }
        return Result.error().message("删除角色失败!");
    }

//  @DeleteMapping("/delete/{id}")
//  public Result delRole(@PathVariable("id") Long id) {
//    if (roleService.deleteRoleById(id)) {
//      return Result.ok().message("删除角色成功!");
//    }
//    return Result.error().message("删除角色失败!");
//  }

    @PostMapping("/test")
    public Result roleTest() {
        try {
            List<FibRoleDTO> allRoles = roleService.getAllRoles();
            log.info("allroles:{}", allRoles);
            HashMap<String, Object> map = new HashMap<>(allRoles.size());
            for (int i = 0; i < allRoles.size(); ++i) {
                map.put(String.valueOf(i + 1), allRoles.get(i));
            }
            return Result.ok().data(map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.error();
    }
}
